# 一口气写完，全对！庆祝一下！

import sys
import pygame

class Rocket():

    def __init__(self):
        pygame.init()
        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((720, 480))
        self.image = pygame.image.load('12_chapter_12_test\\火箭.png')
        self.screen_rect = self.screen.get_rect()
        self.image_rect = self.image.get_rect()
        self.image_rect.center = self.screen_rect.center
        self.image_x = float(self.image_rect.x)
        self.image_y = float(self.image_rect.y)
        self.moving_right = False
        self.moving_left = False
        self.moving_up = False
        self.moving_down = False
        self.speed = 3

    def update(self):
        if self.moving_right and self.image_rect.right < self.screen_rect.right:
            self.image_x += self.speed
        if self.moving_left and self.image_rect.left > 0:
            self.image_x -= self.speed
        if self.moving_up and self.image_rect.top > 0:
            self.image_y -= self.speed
        if self.moving_down and self.image_rect.bottom < self.screen_rect.bottom:
            self.image_y += self.speed
        self.image_rect.x = self.image_x
        self.image_rect.y = self.image_y

    def blitme(self):
        self.screen.blit(self.image, self.image_rect)

    def run_game(self):
        while True:
            self._check_events()
            self.update()
            self._update_screen()
            self.clock.tick(60)


    def _check_events(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                sys.exit()
            elif event.type == pygame.KEYDOWN:
                self._check_keydown_events(event)
            elif event.type == pygame.KEYUP:
                self._check_keyup_events(event)
            

    def _check_keydown_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.moving_right = True
        elif event.key == pygame.K_LEFT:
            self.moving_left = True
        elif event.key == pygame.K_UP:
            self.moving_up = True
        elif event.key == pygame.K_DOWN:
            self.moving_down = True
        elif event.key == pygame.K_q:
            sys.exit()

    def _check_keyup_events(self, event):
        if event.key == pygame.K_RIGHT:
            self.moving_right = False
        elif event.key == pygame.K_LEFT:
            self.moving_left = False
        elif event.key == pygame.K_UP:
            self.moving_up = False
        elif event.key == pygame.K_DOWN:
            self.moving_down = False
    
    def _update_screen(self):
        self.screen.fill((99, 99, 99))
        self.screen.blit(self.image, self.image_rect)
        pygame.display.flip()

rocket = Rocket()
rocket.run_game()